Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 26x 23x 23x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 5x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 2x 5x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 13x 13x 13x 13x 13x 14x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 11x 14x 1x 1x 10x 10x 10x 10x 10x 10x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 6x 6x 14x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 2x 4x 4x 4x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 6x 6x 6x 6x 6x 7x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 4x 7x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x | import { NextRequest, NextResponse } from "next/server";
import {
withAuth,
withErrorHandling,
successResponse,
validationErrorResponse,
ApiError,
ApiSuccessResponse,
ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import { addSecurityHeaders } from "@/lib/security";
import {
checkRateLimit,
rateLimitPresets,
getRateLimitInfo } from "@/lib/security";
import { z } from "zod";
import { Address } from "@prisma/client";
import { Session } from "next-auth";
// Address update schema
const AddressUpdateSchema = z.object({
type: z.enum(["SHIPPING", "BILLING"]).optional(),
// Contact Information
name: z.string().min(1).max(100).optional(),
email: z.string().email().max(255).optional().nullable(),
phone: z.string().max(20).optional().nullable(),
// Address Fields
street: z.string().min(5).max(255).optional(),
city: z.string().min(2).max(100).optional(),
state: z.string().min(2).max(100).optional(),
zipCode: z.string().min(3).max(20).optional(),
country: z.string().min(2).max(100).optional(),
isDefault: z.boolean().optional()});
// Rate limit helper - returns error response if rate limited
function checkRateLimitForAddress(
request: NextRequest,
action: "get" | "patch" | "delete"
): NextResponse<ApiErrorResponse> | null {
const ip =
request.headers.get("x-forwarded-for") ||
request.headers.get("x-real-ip") ||
"unknown";
const key = `api-user-addresses-${action}-id-${ip}`;
if (
!checkRateLimit(
key,
rateLimitPresets.standard.limit,
rateLimitPresets.standard.windowMs
)
) {
//
const rateLimitInfo = getRateLimitInfo(key, rateLimitPresets.standard.limit);
return addSecurityHeaders(
NextResponse.json<ApiErrorResponse>(
{
success: false,
error: {
code: "RATE_LIMIT_EXCEEDED",
message: "Rate limit exceeded"}},
{
status: 429,
headers: {
"X-RateLimit-Limit": rateLimitInfo.limit.toString(),
"X-RateLimit-Remaining": rateLimitInfo.remaining.toString(),
"X-RateLimit-Reset": rateLimitInfo.resetTime}}
)
);
}
return null;
}
// GET /api/user/addresses/[id] - Get specific address
async function handleGet(
request: NextRequest,
context: RouteContext | undefined,
session: Session
): Promise<NextResponse<ApiSuccessResponse<Address> | ApiErrorResponse>> {
// Rate limiting
const rateLimitResponse = checkRateLimitForAddress(request, "get");
if (rateLimitResponse) {
return rateLimitResponse;
}
const { id } = await context!.params!;
const addressId = parseInt(id);
const userId = session.user.id;
if (isNaN(addressId)) {
return addSecurityHeaders(
validationErrorResponse("Invalid address ID", [
{ field: "id", message: "Address ID must be a number", code: "invalid_type" },
])
);
}
// Fetch address (ensure it belongs to current user)
const address = await prisma.address.findFirst({
where: {
id: addressId,
userId}});
if (!address) {
throw ApiError.notFound("Address");
}
return addSecurityHeaders(successResponse(address));
}
// PATCH /api/user/addresses/[id] - Update specific address
async function handlePatch(
request: NextRequest,
context: RouteContext | undefined,
session: Session
): Promise<NextResponse<ApiSuccessResponse<Address> | ApiErrorResponse>> {
// Rate limiting
const rateLimitResponse = checkRateLimitForAddress(request, "patch");
if (rateLimitResponse) {
return rateLimitResponse;
}
const { id } = await context!.params!;
const addressId = parseInt(id);
const userId = session.user.id;
if (isNaN(addressId)) {
return addSecurityHeaders(
validationErrorResponse("Invalid address ID", [
{ field: "id", message: "Address ID must be a number", code: "invalid_type" },
])
);
}
// Verify address belongs to user
const existingAddress = await prisma.address.findFirst({
where: {
id: addressId,
userId}});
if (!existingAddress) {
throw ApiError.notFound("Address");
}
const body = await request.json();
// Validate input
const validationResult = AddressUpdateSchema.safeParse(body);
if (!validationResult.success) {
return addSecurityHeaders(
validationErrorResponse(
"Invalid address data",
validationResult.error.issues.map((issue) => ({
field: issue.path.join(".") || "_root",
message: issue.message,
code: issue.code}))
)
);
}
const validatedData = validationResult.data;
// If setting as default, unset other defaults of the same type
let updatedAddress: Address;
if (validatedData.isDefault) {
const addressType = validatedData.type || existingAddress.type;
updatedAddress = await prisma.$transaction(async (tx) => {
// Unset other defaults of the same type
await tx.address.updateMany({
where: {
userId,
type: addressType,
isDefault: true,
id: { not: addressId }},
data: { isDefault: false }});
// Update address
return await tx.address.update({
where: { id: addressId },
data: validatedData});
});
} else {
updatedAddress = await prisma.address.update({
where: { id: addressId },
data: validatedData});
}
return addSecurityHeaders(successResponse(updatedAddress));
}
// DELETE /api/user/addresses/[id] - Delete specific address
async function handleDelete(
request: NextRequest,
context: RouteContext | undefined,
session: Session
): Promise<NextResponse<ApiSuccessResponse<{ message: string }> | ApiErrorResponse>> {
// Rate limiting
const rateLimitResponse = checkRateLimitForAddress(request, "delete");
if (rateLimitResponse) {
return rateLimitResponse;
}
const { id } = await context!.params!;
const addressId = parseInt(id);
const userId = session.user.id;
if (isNaN(addressId)) {
return addSecurityHeaders(
validationErrorResponse("Invalid address ID", [
{ field: "id", message: "Address ID must be a number", code: "invalid_type" },
])
);
}
// Verify address belongs to user
const existingAddress = await prisma.address.findFirst({
where: {
id: addressId,
userId}});
if (!existingAddress) {
throw ApiError.notFound("Address");
}
// Delete address
await prisma.address.delete({
where: { id: addressId }});
return addSecurityHeaders(
successResponse({ message: "Address deleted successfully" })
);
}
export const GET = withErrorHandling(withAuth(handleGet));
export const PATCH = withErrorHandling(withAuth(handlePatch));
export const DELETE = withErrorHandling(withAuth(handleDelete));
|